//
//  MPTDeviceOrientationDetector.m
//  MiaoPai
//
//  Created by Khazmovsky on 16/6/22.
//  Copyright © 2016年 Jeakin. All rights reserved.
//

#import "MPTDeviceOrientationDetector.h"
#import <CoreMotion/CoreMotion.h>

@interface MPTDeviceOrientationDetector () {
    CMMotionManager *motionManager;
}

@property (nonatomic, assign) UIDeviceOrientation currentDeviceOrientation;

@end

@implementation MPTDeviceOrientationDetector

+ (MPTDeviceOrientationDetector *)sharedDetector {
    static MPTDeviceOrientationDetector *ins = nil;
    static dispatch_once_t onceToken;
    _dispatch_once(&onceToken, ^{
        ins = [self new];
    });
    return ins;
}

- (instancetype)init {
    if (self = [super init]) {
        motionManager = [CMMotionManager new];
        motionManager.accelerometerUpdateInterval = 1.0;
    }
    return self;
}

- (void)beginUpdates {
    [motionManager startAccelerometerUpdates];
}

- (void)endUpdates {
    [motionManager stopAccelerometerUpdates];
}

- (UIDeviceOrientation)currentDeviceOrientation {
    if (motionManager.accelerometerData) {
        _currentDeviceOrientation = [self deviceOrientationForAccleration:motionManager.accelerometerData.acceleration];
    }
    return _currentDeviceOrientation;
}

- (UIDeviceOrientation)deviceOrientationForAccleration:(CMAcceleration)acceleration {
    UIDeviceOrientation orientationNew = UIDeviceOrientationUnknown;
    if (acceleration.x >= 0.75) {
        orientationNew = UIDeviceOrientationLandscapeLeft;
    } else if (acceleration.x <= -0.75) {
        orientationNew = UIDeviceOrientationLandscapeRight;
    } else if (acceleration.y <= -0.75) {
        orientationNew = UIDeviceOrientationPortrait;
    } else if (acceleration.y >= 0.75) {
        orientationNew = UIDeviceOrientationPortraitUpsideDown;
    }
    return orientationNew;
}

@end
